package com.alipay.service.rpc;

import com.alipay.mapper.RedBagMapper;
import com.alipay.mapper.RedBagTransMapper;
import com.alipay.model.dto.TransDto;
import com.alipay.model.enums.RefundStatusEnum;
import com.alipay.model.enums.TransStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 *
 * @author Jun
 * @date 2019/3/24
 */
@Service
@Slf4j
public class TransService {

    @Autowired
    private RedBagTransMapper redBagTransMapper;

    @Autowired
    private RedBagMapper redBagMapper;


    /**
     * 异步转账服务
     * @param transDto
     */
    @Async
    public void trans(TransDto transDto){
        try {
            // 调用转账系统，实现省略
            redBagTransMapper.updateStatus(transDto.getRedBagNo(), transDto.getUserId(), TransStatusEnum.SUCCESS.getStatus());
        }catch (Exception e){
            log.warn("trans error, e={}", e);
            redBagTransMapper.updateStatus(transDto.getRedBagNo(), transDto.getUserId(), TransStatusEnum.INIT.getStatus(), TransStatusEnum.FAIL.getStatus());
        }
    }

    /**
     * 红包退款
     * @param transDto
     */
    public void refund(TransDto transDto){
        try {
            // 调用转账系统，实现省略
            redBagMapper.updateRefundStatus(transDto.getRedBagNo(), RefundStatusEnum.REFUND.getStatus());
        }catch (Exception e){
            log.error("退款失败，redBagNo={}, e={}", transDto.getRedBagNo(), e);
            // 设置退款状态为失败，用补偿机制重新发起退款
            redBagMapper.updateRefundStatus(transDto.getRedBagNo(), RefundStatusEnum.FAILED.getStatus());
        }
    }

    /**
     * 发红包时，异步通知用户付款
     * @param transDto
     * @param callbackUrl
     */
    @Async
    public void noticePay(TransDto transDto, String callbackUrl){
        // 实现省略
    }
}
